//
//  GiveBackCarOwnerPhotoCollectionViewController.m
//  UcarTest
//
//  Created by 陈曦 on 16/3/24.
//  Copyright © 2016年 chenxi. All rights reserved.
//

#import "GiveBackCarOwnerPhotoCollectionViewController.h"
#import "AFNetworking.h"
#import "NetRequestGroup.h"
#import "Access_token.h"
#import "MBProgressHUD.h"
#import "Define.h"
#import "STPhotoKitController.h"
#import "UIImagePickerController+ST.h"
#import "STConfig.h"


@interface GiveBackCarOwnerPhotoCollectionViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate, UIActionSheetDelegate, STPhotoKitDelegate>

//存储model的数组
@property (strong, nonatomic) NSMutableArray *array;

@property (nonatomic, strong) PhotoCollectionViewCell *cell;

@end

@implementation GiveBackCarOwnerPhotoCollectionViewController

static NSString * const reuseIdentifier = @"Cell";


-(void)loadView
{
    
    //创建集合视图的布局
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    //
    
    
    layout.itemSize = CGSizeMake((kScreenWidth - 42)  / 3, (kScreenWidth - 42) / 3 + 20);
    
    
    [layout setSectionInset:UIEdgeInsetsMake(7, 7, 7, 7)];
    
    //    layout.headerReferenceSize = CGSizeMake(kScreenWidth, 30);
    //创建集合视图
    UICollectionView *todayCV = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout: layout];
    self.collectionView = todayCV;
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    //导航条设置
    [self navigationItemSet];
    
    //基本设置
    self.collectionView.backgroundColor = backgroundMainColor;
    self.collectionView.delegate = self;
    
    self.collectionView.dataSource = self;
    
    //初始化数组
    self.array = [NSMutableArray array];
    self.checkOutModel = [[CheckOutPhotoCarOwnerModel alloc] init];
    self.checkOutModel.add_time = 0;
    [self.array addObject:self.checkOutModel];
    
    
    [self.collectionView registerClass:[PhotoCollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
    
    [self NetworkRequests];
    
}



#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 1;
    
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.array.count;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    self.cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    if (indexPath.row == 0) {
        
        self.cell.photoImageV.image = [UIImage imageNamed:@"ico_photo_button"];
        
        self.cell.timeLabel.text = @"";
        
    } else if(indexPath.row > 0) {
        
        self.cell.model = self.array[indexPath.row];
        
    }
    return self.cell;
}

#pragma mark <UICollectionViewDelegate>

#pragma mark ---点击cell事件---
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        
        [self editImageSelected];
        
    } else {
        
        self.cell.model = self.array[indexPath.row];

        
        [self bigImage:self.cell.photoImageV.image];
        
    }
    
}


//========================================================================

#pragma mark 点击图片放大

- (void) bigImage:(UIImage *)image {
    
    // iOS7后,[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
    
    [self prefersStatusBarHidden];
    
    

    self.navigationController.navigationBarHidden = YES;
    //蒙板
    self.menbanView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    self.menbanView.backgroundColor = [UIColor blackColor];
    
    [self.view addSubview:self.menbanView];
    
    self.bigImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, (kScreenHeight -(kScreenWidth / 1.6)) / 2, kScreenWidth, kScreenWidth / 1.6)];
    
    self.bigImageView.image = image;
    
    [self.view addSubview:self.bigImageView];
    
    //滑动手势
    self.panMove = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    [self.view addGestureRecognizer:self.panMove];
    [self.panMove setCancelsTouchesInView:YES];
    self.panMove.delegate = self;

    
}

- (void) handlePan: (UIPanGestureRecognizer *)rec{
    
    self.navigationController.navigationBarHidden = NO;
    
    [self prefersStatusBarHidden];

    [self.menbanView removeFromSuperview];
    
    [self.bigImageView removeFromSuperview];
    
}



//========================================================================


#pragma mark 网络请求
- (void) NetworkRequests{
    
    //初始化进度框，置于当前的View当中
    MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
    HUD.label.text = @"正在加载";
    [HUD showAnimated:YES];//HUD开始
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //申明返回的结果是json类型
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    //申明请求的数据是json类型
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //如果报接受类型不一致请替换一致text/html或别的
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    Access_token *useAccess = [Access_token shareInstance];
    
    //传入的参数
    NSDictionary *para = @{
                           @"type" : @"1",
                           @"access_token" : useAccess.access_token,
                           @"order_id" : self.order_id,
                           @"order_type" : @"1",
                           @"img_type" : @"1"
                           };
    //你的接口地址
    NSString *url = [NSString stringWithFormat:@"%@%@", kRealmName,kNetrorderlistorderimg];
    //发送请求
    [manager POST:url parameters:para success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [HUD hideAnimated:YES];
        
        NSDictionary *dic = responseObject;
        
        self.status = dic[@"status"];
        
        self.msg = dic[@"msg"];
        
        NSDictionary *info = dic[@"info"];
        
        for (NSDictionary *dic in info[@"list"]) {
            
            CheckOutPhotoCarOwnerModel *checkOutPhotoModel = [[CheckOutPhotoCarOwnerModel alloc] init];
            [checkOutPhotoModel setValuesForKeysWithDictionary:dic];
            
            [self.array addObject:checkOutPhotoModel];
            
            [self.collectionView reloadData];
            
        }
        
        [self resultAnalysis];

        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [HUD hideAnimated:YES];
        
        //初始化提示框；
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"没有网络" preferredStyle:  UIAlertControllerStyleAlert];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //点击按钮的响应事件；
        }]];
        
        //弹出提示框；
        [self presentViewController:alert animated:true completion:nil];
        
    }];
    
}
//========================================================================

#pragma mark - --- event response 事件相应 ---
- (void)editImageSelected
{
    UIAlertController *alertController = [[UIAlertController alloc]init];
    
    UIAlertAction *action0 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *controller = [UIImagePickerController imagePickerControllerWithSourceType:UIImagePickerControllerSourceTypeCamera];
        
        if ([controller isAvailableCamera] && [controller isSupportTakingPhotos]) {
            [controller setDelegate:self];
            [self presentViewController:controller animated:YES completion:nil];
        }else {
        }
    }];
    
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [alertController addAction:action0];
//    [alertController addAction:action1];
    [alertController addAction:action2];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - 2.UIImagePickerController的委托

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        UIImage *imageOriginal = [info objectForKey:UIImagePickerControllerOriginalImage];
        STPhotoKitController *photoVC = [STPhotoKitController new];
        [photoVC setDelegate:self];
        [photoVC setImageOriginal:imageOriginal];
        [photoVC setSizeClip:CGSizeMake(kScreenWidth, kScreenWidth / 1.6)];
        
        [self presentViewController:photoVC animated:YES completion:nil];
        
    }];
}

- (void)photoKitController:(STPhotoKitController *)photoKitController resultImage:(UIImage *)resultImage {
    
    
    //设置一个图片的存储路径
    NSString *path_sandox = NSHomeDirectory();
    
    NSString *imagePath = [path_sandox stringByAppendingString:@"/Documents/UpIDImage.png"];
    //把图片直接保存到指定的路径（同时应该把图片的路径imagePath存起来，下次就可以直接用来取）
    [UIImagePNGRepresentation(resultImage) writeToFile:imagePath atomically:YES];
    
    UIImage *imgFromUrl3=[[UIImage alloc]initWithContentsOfFile:imagePath];
    
    NSData* imageData = UIImagePNGRepresentation(imgFromUrl3);
    
    self.upImageBase64Str = [imageData base64Encoding];
    
    
    [self ImageNetworkRequests];
    
    
}




//========================================================================

#pragma mark 上传图片网络请求
- (void) ImageNetworkRequests{
    
    
    
    //初始化进度框，置于当前的View当中
    MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
    HUD.label.text = @"正在加载";
    [HUD showAnimated:YES];//HUD开始
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //申明返回的结果是json类型
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    //申明请求的数据是json类型
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //如果报接受类型不一致请替换一致text/html或别的
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    Access_token *useAccess = [Access_token shareInstance];
    
    //传入的参数
    NSDictionary *para = @{
                           @"type" : @"1",
                           @"access_token" : useAccess.access_token,
                           @"imageFile" : self.upImageBase64Str,
                           @"order_id" : self.order_id,
                           @"order_type" : @"1",
                           @"img_type" : @"1"
                           };
    //你的接口地址
    NSString *url = [NSString stringWithFormat:@"%@%@", kRealmName, kNetrorderaddorderimg];
    //发送请求
    [manager POST:url parameters:para success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [HUD hideAnimated:YES];
        
        
        NSDictionary *dic = responseObject;
        
        self.upImageStatus = dic[@"status"];
        
        self.upImageMsg = dic[@"msg"];
        
        NSDictionary *info = dic[@"info"];
        
        CheckOutPhotoCarOwnerModel *checkOutPhotoModel = [[CheckOutPhotoCarOwnerModel alloc] init];
        
        [checkOutPhotoModel setValuesForKeysWithDictionary:info];
        
        [self.array addObject:checkOutPhotoModel];
        
        [self.collectionView reloadData];
        
        
        [self upImageResultAnalysis];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [HUD hideAnimated:YES];
        
        //初始化提示框；
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"没有网络" preferredStyle:  UIAlertControllerStyleAlert];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //点击按钮的响应事件；
        }]];
        
        //弹出提示框；
        [self presentViewController:alert animated:true completion:nil];
    }];
    
    
    
}





//========================================================================


#pragma mark 正面照返回值分析
- (void) upImageResultAnalysis {
    
    int status = [self.upImageStatus intValue];
    
    switch (status) {
        case 99:{
            //初始化提示框；
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:self.upImageMsg preferredStyle:  UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //点击按钮的响应事件；
            }]];
            
            //弹出提示框；
            [self presentViewController:alert animated:true completion:nil];
            
        }
            
            break;
        case 98:{
            
            //初始化提示框；
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:self.upImageMsg preferredStyle:  UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //点击按钮的响应事件；
            }]];
            
            //弹出提示框；
            [self presentViewController:alert animated:true completion:nil];
            
        }
            break;
        case 97:
        {
            //初始化提示框；
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:self.upImageMsg preferredStyle:  UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //点击按钮的响应事件；
            }]];
            
            //弹出提示框；
            [self presentViewController:alert animated:true completion:nil];
            
        }
            
            break;
        case 96:
        {
            
            //初始化提示框；
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:self.upImageMsg preferredStyle:  UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //点击按钮的响应事件；
            }]];
            
            //弹出提示框；
            [self presentViewController:alert animated:true completion:nil];
            
        }
            
            break;
        case 1:
        {
            //初始化提示框；
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:self.upImageMsg preferredStyle:  UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //点击按钮的响应事件；
            }]];
            
            //弹出提示框；
            [self presentViewController:alert animated:true completion:nil];
            
        }
            break;
            
        case 2:
        {
            //初始化提示框；
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:self.upImageMsg preferredStyle:  UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //点击按钮的响应事件；
            }]];
            
            //弹出提示框；
            [self presentViewController:alert animated:true completion:nil];
            
        }
            break;
            
        case 100:
        {
            
            //初始化提示框；
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:self.upImageMsg preferredStyle:  UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                //点击按钮的响应事件；
                
                
                
            }]];
            
            //弹出提示框；
            [self presentViewController:alert animated:true completion:nil];
            
        }
            break;
            
        default:
            break;
    }
    
    
    
}




//========================================================================















#pragma mark 导航条设置
//导航条设置========================================================================
- (void) navigationItemSet {
    self.navigationController.navigationBarHidden = NO;
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.font = [UIFont boldSystemFontOfSize:18];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = @"还车照片";
    self.navigationItem.titleView = titleLabel;
    self.navigationController.navigationBar.barTintColor = mainColor;
    self.view.backgroundColor = backgroundMainColor;
    
    //重定义返回键
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    back.frame = CGRectMake(0, 0, 22, 22);
    [back setImage:[UIImage imageNamed:@"iconfont-fanhui-white"] forState:UIControlStateNormal];
    [back addTarget:self action:@selector(backTpMainView) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backBar = [[UIBarButtonItem alloc] initWithCustomView:back];
    self.navigationItem.leftBarButtonItem = backBar;
    
}

//返回上一页
- (void)backTpMainView{
    
    [self.navigationController popViewControllerAnimated:nil];
    
}
#pragma mark 返回值分析
- (void) resultAnalysis {
    
    int status = [self.status intValue];
    
    switch (status) {
        case 99:{
            //初始化提示框；
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:self.msg preferredStyle:  UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //点击按钮的响应事件；
            }]];
            
            //弹出提示框；
            [self presentViewController:alert animated:true completion:nil];
            
        }
            
            break;
        case 98:{
            
            //初始化提示框；
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:self.msg preferredStyle:  UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //点击按钮的响应事件；
            }]];
            
            //弹出提示框；
            [self presentViewController:alert animated:true completion:nil];
            
        }
            break;
        case 97:
        {
            //初始化提示框；
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:self.msg preferredStyle:  UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //点击按钮的响应事件；
            }]];
            
            //弹出提示框；
            [self presentViewController:alert animated:true completion:nil];
            
        }
            
            break;
        case 96:
        {
            
            //初始化提示框；
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:self.msg preferredStyle:  UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //点击按钮的响应事件；
            }]];
            
            //弹出提示框；
            [self presentViewController:alert animated:true completion:nil];
            
        }
            
            break;
        case 1:
        {
            //初始化提示框；
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:self.msg preferredStyle:  UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //点击按钮的响应事件；
            }]];
            
            //弹出提示框；
            [self presentViewController:alert animated:true completion:nil];
            
        }
            break;
            
            
        case 100:
        {
            
            //初始化提示框；
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:self.msg preferredStyle:  UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                //点击按钮的响应事件；
                
                
                
            }]];
            
            //弹出提示框；
            [self presentViewController:alert animated:true completion:nil];
            
        }
            break;
            
        default:
            break;
    }
    
    
    
}

@end
